package com.katze.boot.plugins.knife4j;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.configuration.OpenApiDocumentationConfiguration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 说  明：Knife4j在线API接口
 * 作  者：zf.zeng
 * 日  期：2022-09-30 (星期五)
 **/
@Configuration
@Import({OpenApiDocumentationConfiguration.class})
public class Knife4jConfig {


    @Bean
    @ConditionalOnProperty(prefix = "knife4j", name = "enable", havingValue = "true")
    public Docket createRestApi(Knife4jExtendProperties knife4jExtendProperties) {
        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .apiInfo(apiInfo(knife4jExtendProperties))
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.katze.boot"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(Knife4jExtendProperties properties) {
        return new ApiInfoBuilder()
                .description(properties.getDescription())
                .contact(new Contact(properties.getAuthor(), properties.getUrl(), properties.getEmail()))
                .license(properties.getLicense()).licenseUrl(properties.getLicenseUrl())
                .version(properties.getVersion())
                .title(properties.getTitle())
                .build();
    }

    /**
     * 增加如下配置可解决Spring Boot 6.x 与Swagger 3.0.0 不兼容问题
     **/
    @Bean
    public static BeanPostProcessor springFoxHandlerProviderBeanPostProcessor() {
        //重新注入后置处理器
        return new BeanPostProcessor() {

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            //过滤掉
            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                mappings.removeIf(mapping -> mapping.getPatternParser() != null);
            }

            @SuppressWarnings("unchecked") //忽略警告
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try { //反射找到handlerMappings
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }
}
